﻿package com.cenfun.ui {
	public dynamic class TN {
		public var opened:Boolean;
		public var parent:TN;
		public var level:Number;
		public var nodeType:String;
		public var children:Array;
		public var treeData:TD;
		public function TN(td:TD, xml:XML, _parent:TN, _level:int):void {
			treeData = td;
			parent = _parent;
			level = _level;
			//获取外设属性列表
			var attrs:XMLList = xml.attributes();
			for each (var attr:XML in attrs) {
				this[attr.localName()] = attr.toString();
			}
			//初始化特殊属性
			children = [];
			//子节点
			if (xml.hasComplexContent()) {
				nodeType = TD.NODE_L;
				for each (var child:XML in xml.children()) {
					var childNode:TN = new TN(td, child, this, level + 1);
					children.push(childNode);
				}
			} else {
				nodeType = TD.NODE_M;
				this[null] = xml.text();
			}
		}
		//===========================================================================
		public function open():void {
			if (nodeType == TD.NODE_L) {
				opened = true;
				show();
			}
		}
		public function close():void {
			if (nodeType == TD.NODE_L) {
				opened = false;
				hide();
			}
		}
		
		public function toggle():void {
			if (opened) {
				close();
			} else {
				open();
			}
		}
		//返回最后一个子节点的位置 
		public function show():int {
			//父节点位置
			var myIndex:int = treeData.getItemIndex(this);
			//当前正在添加到的位置
			var index:int = 0;
			for (var i:int = 0; i < children.length; i ++) {
				var child:TN = children[i];
				index += 1;
				treeData.addItemAt(child, myIndex + index);
				if (child.opened) {
					index += child.show();
				}
			}
			return index;
		}
		public function hide():void {
			var myIndex:int = treeData.getItemIndex(this);
			for each(var child:TN in children) {
				treeData.removeItem(child);
				child.hide();
			}
		}
		


	}

}